package com.neusoft.neuiotms.dcam.common.repository.impl;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import com.neusoft.bizcore.web.jpa.repository.AbstractRepository;
import com.neusoft.bizcore.web.support.Searchable;
import com.neusoft.neuiotms.dcam.common.model.Manufacturer;
import com.neusoft.neuiotms.dcam.common.model.QManufacturer;
import com.neusoft.neuiotms.dcam.common.repository.CustomizedManufacturerRepository;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.jpa.impl.JPAQuery;

public class CustomizedManufacturerRepositoryImpl extends AbstractRepository
        implements CustomizedManufacturerRepository {

    @Override
    public Page<Manufacturer> search(final Pageable pageable, final Searchable searchable) {
        final QManufacturer qManufacturer = QManufacturer.manufacturer;
        final BooleanBuilder where = this.buildWhere(searchable);
        final JPAQuery<Manufacturer> query = this.query().selectFrom(qManufacturer);
        query.where(where);
        return super.search(query, pageable);
    }

    @Override
    protected Class<?> getModelClass() {
        return Manufacturer.class;
    }

    private BooleanBuilder buildWhere(final Searchable searchable) {
        final BooleanBuilder where = new BooleanBuilder();
        final QManufacturer qManufacturer = QManufacturer.manufacturer;

        if (!StringUtils.isEmpty(searchable.getStrValue("name"))) {
            where.or(super.containsStr(qManufacturer.name, searchable, "name"));
            where.or(super.containsStr(qManufacturer.person, searchable, "name"));
        }

        if (!StringUtils.isEmpty(searchable.getStrValue("phone"))) {
            where.or(super.containsStr(qManufacturer.phone, searchable, "phone"));
        }

        if (!StringUtils.isEmpty(searchable.getStrValue("status"))) {
            where.or(super.equalsBool(qManufacturer.status, searchable, "status"));
        }

        return where;
    }

}
